<template>
  <q-layout view='lHh Lpr lFf'>
    <!--    头部-->
    <q-header elevated id="header">
      <q-toolbar>
        <q-btn flat dense round icon='menu' aria-label='Menu' @click='toggleLeftDrawer' />
        <q-toolbar-title>
        </q-toolbar-title>
      </q-toolbar>
    </q-header>
    <!--    左侧栏抽屉-->
    <q-drawer v-model='leftDrawerOpen' show-if-above bordered class='bg-grey-1'>
      <div class='q-pa-md q-gutter-sm'>
        <q-tree selected-color='primary' :nodes='linksList.arr' accordion node-key='labelKey'
          v-model:selected='selectedKey' v-model:expanded='expandedKeys' @update:selected='onMenuSelected()'
          @update:expanded='onMenuExpanded()' default-expand-all />
      </div>
    </q-drawer>
    <q-page-container :style="{
      width: spaceForRight == '' ? '100%' : ('calc(100% - ' + spaceForRight + ')')
    }">
      <router-view @rightInfo="handleRightRefresh" />
    </q-page-container>
  </q-layout>
  <right :refresh="refresh" @changeDisplay="handleRightChangeDisplay"></right>
</template>
<script lang='ts'>
import { defineComponent, onMounted, ref, reactive } from 'vue';
import { ChannelRouteQuery, Links } from 'components/models';
import { postRequest, getEntityCode } from '../components/functions';
import { useStore } from 'src/store';
import { useRouter } from 'vue-router';
import { api } from 'boot/axios';
import right from '../right/right.vue'

export default defineComponent({
  name: 'MainLayout',
  components: { right },
  data() {
    return {
      refresh: {},
      spaceForRight: '',
    }
  },
  methods: {
    handleRightChangeDisplay(e) {
      if (e.code == 1) {
        this.spaceForRight = e.width
      }
      if (e.code == 0) {
        this.spaceForRight = ''
      }
    },
    handleRightRefresh(e) {
      this.refresh = e
    },
    waitSeconds(n) {
      return new Promise<void>((resolve, reject) => {
        setTimeout(() => {
          resolve()
        }, n * 1000);
      })
    }
  },
  async mounted() {

  },
  setup() {
    const leftDrawerOpen = ref(false);
    const userData = useStore().state.sphinx.userData;
    const router = useRouter();
    let linksList = reactive({ arr: [] });
    let selectedKey = ref<string>('');
    let expandedKeys = ref<string>('');
    let expandedEntityCode = ref<string>('');
    let isExpanded = ref<boolean>(false);

    /**
     * 获取左侧栏列项
     */
    function getLinks(): void {
      let sceneCode = ''
      let requestSceneBody = [
        {
          "entityCode": '101',
          "codeName": '',
          "entityType": '01',
          "typeName": '',
          "eventCode": null,
          "eventName": null,
          "propertyEnglish": null,
          "propertyChinese": null,
          "propertyValue": null,
          "propertyCondition": null,
          "companyId": userData.companyId
        },
        {
          "entityCode": '102',
          "codeName": '',
          "entityType": '02',
          "typeName": '',
          "eventCode": null,
          "eventName": null,
          "propertyEnglish": 'roleType',
          "propertyChinese": null,
          "propertyValue": userData.roleType,
          "propertyCondition": null,
          "companyId": userData.companyId
        }];
      api.post('/channel/channel/getSceneCode', requestSceneBody).then(res => {
        if (res.status == 200) {
          sceneCode = res.data.data
          let apiByInterfaceEnglish = reactive({ entityCode: '001', groupEntityCode: '101', theirEventCode: '' });//主页面001,群主体：渠道101
          let reqData = {
            entityCode: apiByInterfaceEnglish.entityCode,
            // entityType: apiByInterfaceEnglish.entityType,
            entityType: '101',
            sceneCode: sceneCode,//渠道101+当事人102+用户角色userData.roleType（例：01为管理员）
            objectCodeType: '101',//主页面菜单
            // propertyCode: '101',
            companyId: userData.companyId,
            groupEntityCode: apiByInterfaceEnglish.groupEntityCode
            // theirEventCode: apiByInterfaceEnglish.theirEventCode
          };
          postRequest('channel/channel/queryMenu', reqData, setLinks);
        }
      })
    }

    /**
     * 设置左侧栏
     * @param links
     */
    function setLinks(links: any): void {
      let faArr = reactive([]);
      let childArr = reactive([]);
      for (let i = 0; i < links.length; i++) {
        if (links[i].entityType == '01') {
          links[i].MenusEntity.forEach((item: { property_name: any; property_code: any; }) => {
            faArr.push({
              label: item.property_name,
              labelKey: item.property_code
            });
          });
        } else {
          childArr.push(links[i]);
        }
      }
      for (let i = 0; i < faArr.length; i++) {
        for (let x = 0; x < childArr.length; x++) {
          let entityT = ref<string>(childArr[x].entityType.substr(2));
          if (faArr[i].labelKey == entityT.value) {
            let sonArr = reactive([]);
            childArr[x].MenusEntity.forEach((item: { property_name: any; property_code: any; }) => {
              let obj = { label: '', labelKey: '' };
              obj.label = item.property_name;
              obj.labelKey = faArr[i].labelKey + '/' + item.property_code;
              sonArr.push(obj);
              faArr[i].children = sonArr;
            });
          }
        }
      }
      linksList.arr = faArr;
      console.log("linksList.arr", linksList.arr);

    }
    const store = useStore();
    // 点击菜单栏跳往list页面
    function onMenuSelected() {
      let string = selectedKey?.value?.split("/")[1];
      let childKey = string === undefined ? selectedKey?.value : string;
      store.commit('sphinx/updateRouterPath', []);
      store.commit('sphinx/updateParentEntity', []);
      store.commit('sphinx/updateSelectedItemData', []);
      console.log("selectedKey.value", selectedKey.value);

      void router.push('/');
      if (childKey?.length == 3) {
        setTimeout(() => {
          void router.push('/list?entityCode=' + childKey + '&flag=' + 1);
        }, 10);
      } else if (childKey?.length == 2) {
        if (childKey == "03" && expandedEntityCode.value == "301") {
          setTimeout(() => {
            void router.push('/BatchPrice?entityCode=' + expandedEntityCode.value + '&childCode=' + childKey);
          }, 10);
        } else {
          setTimeout(() => {
            void router.push('/list?entityCode=' + expandedEntityCode.value + '&childCode=' + childKey + '&flag=' + 1);
          }, 10);
        }
      } else {
        setTimeout(() => {
          void router.push('/list?entityCode=' + expandedEntityCode.value + '&childCode=' + childKey + '&flag=' + 1);
        }, 10);
      }
    }

    function onMenuExpanded() {
      // console.log("expandedKeys.value[0]",expandedKeys.value[0]);  // 菜单选中序号
      // isExpanded.value = false;
      expandedEntityCode.value = expandedKeys.value[0];
    }

    onMounted(() => {
      if (userData.userId !== undefined) {
        getLinks();
      } else {
        void router.push('/login');
      }
    });
    return {
      expandedKeys,
      selectedKey,
      isExpanded,
      expandedEntityCode,
      linksList,
      leftDrawerOpen,
      onMenuSelected,
      onMenuExpanded,
      toggleLeftDrawer() {
        leftDrawerOpen.value = !leftDrawerOpen.value;
      }
    };
  }
});
</script>
